<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>小学口算题生成器</title>
  <style>
    body {
      font-family: sans-serif;
      padding: 20px;
      max-width: 800px;
      margin: auto;
    }

    h2 {
      font-size: 1.5em;
      text-align: center;
    }

    .controls {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-bottom: 15px;
    }

    .controls label,
    .controls input,
    .controls button {
      font-size: 1em;
    }

    .controls input[type="number"] {
      width: 60px;
    }

    .timer {
      margin: 10px 0;
      color: green;
      font-weight: bold;
    }

    .question-list {
      font-size: 1.1em;
      font-weight: bold;
      line-height: 1.8;
    }

    @media (max-width: 600px) {
      .controls {
        flex-direction: column;
        align-items: flex-start;
      }

      .controls input[type="number"] {
        width: 100%;
      }

      .question-list {
        font-size: 1em;
      }

      h2 {
        font-size: 1.3em;
      }
    }
  </style>
</head>
<body>
  <h2>小学三数口算题生成器</h2>

  <div class="controls">
    <label><input type="checkbox" id="add" checked /> 加法（+）</label>
    <label><input type="checkbox" id="sub" checked /> 减法（−）</label>
    <label><input type="checkbox" id="mul" checked /> 乘法（×）</label>
    <label><input type="checkbox" id="div" checked /> 除法（÷）</label>

    <label>最小值：<input type="number" id="min" value="1" min="1" /></label>
    <label>最大值：<input type="number" id="max" value="20" min="1" /></label>
    <label>题目数量：<input type="number" id="count" value="10" min="1" /></label>

    <button onclick="generateQuestions()">生成题目</button>
    <button onclick="showAnswers()">显示答案</button>
  </div>

  <div class="timer" id="timer">已用时间：0 秒</div>
  <div class="question-list" id="questionList">题目将在这里显示</div>

  <script>
    let timerInterval;
    let elapsedSeconds = 0;
    let generatedQuestions = [];

    function startTimer() {
      clearInterval(timerInterval);
      elapsedSeconds = 0;
      document.getElementById('timer').innerText = '已用时间：0 秒';
      timerInterval = setInterval(() => {
        elapsedSeconds++;
        document.getElementById('timer').innerText = `已用时间：${elapsedSeconds} 秒`;
      }, 1000);
    }

    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    function getOperators() {
      const ops = [];
      if (document.getElementById('add').checked) ops.push('+');
      if (document.getElementById('sub').checked) ops.push('-');
      if (document.getElementById('mul').checked) ops.push('*');
      if (document.getElementById('div').checked) ops.push('/');
      return ops;
    }

    function getRandomFromArray(arr) {
      return arr[Math.floor(Math.random() * arr.length)];
    }

    function generateMultiplication() {
      const a = getRandomInt(1, 9);
      const b = getRandomInt(1, 9);
      return [a, '*', b];
    }

    function generateDivision() {
      const b = getRandomInt(1, 9);
      const a = b * getRandomInt(1, 9);
      return [a, '/', b];
    }

    function generateOneOp(min, max, op, prevOp = null) {
      let a, b;

      // 防止连乘或连除
      if ((prevOp === '*' || prevOp === '/') && (op === '*' || op === '/')) {
        // 改成加减之一
        const altOps = ['+', '-'];
        op = altOps[getRandomInt(0, altOps.length - 1)];
      }

      if (op === '+') {
        a = getRandomInt(min, max);
        b = getRandomInt(min, max);
      } else if (op === '-') {
        a = getRandomInt(min, max);
        b = getRandomInt(min, Math.min(a, max)); // 先保证a >= b，避免负数
      } else if (op === '*') {
        [a, , b] = generateMultiplication();
      } else if (op === '/') {
        [a, , b] = generateDivision();
      }

      return [a, op, b];
    }

    function generateOneQuestion(min, max, ops) {
      let a, op1, b, op2, c,display,answer;

      while (true) {
        op1 = getRandomFromArray(ops);
        [a, op1, b] = generateOneOp(min, max, op1);

        op2 = getRandomFromArray(ops);
        // 防止连乘连除
        if ((op1 === '*' || op1 === '/') && (op2 === '*' || op2 === '/')) {
          // 换成加减中随机一个
          const altOps = ops.filter(o => o === '+' || o === '-');
          if (altOps.length > 0) {
            op2 = getRandomFromArray(altOps);
          } else {
            // 如果加减都没选，重新生成
            continue;
          }
        }

        [b, op2, c] = generateOneOp(min, max, op2, op1);

        // 减法导致负数则交换顺序
        if (op1 === '-' && a - b < 0) {
          [a, b] = [b, a];
        }
        if (op2 === '-' && b - c < 0) {
          [b, c] = [c, b];
        }

        // 除法检查：除数不为0且能整除
        if (op1 === '/') {
          if (b === 0 || a % b !== 0) continue;
        }
        if (op2 === '/') {
          if (c === 0 || b % c !== 0) continue;
        }
         display = `${a} ${op1.replace('*', '×').replace('/', '÷')} ${b} ${op2.replace('*', '×').replace('/', '÷')} ${c}`;
        answer = eval(`${a}${op1}${b}${op2}${c}`);
        if(answer<0){
            continue;
        }
        break;
      }

      
      return { display, answer };
    }

    function generateQuestions() {
      const min = parseInt(document.getElementById('min').value) || 1;
      const max = parseInt(document.getElementById('max').value) || 20;
      const count = parseInt(document.getElementById('count').value) || 10;
      const ops = getOperators();

      if (ops.length === 0) {
        document.getElementById('questionList').innerText = '请至少选择一种运算符';
        return;
      }

      generatedQuestions = [];
      for (let i = 0; i < count; i++) {
        generatedQuestions.push(generateOneQuestion(min, max, ops));
      }

      renderQuestions(false);
      startTimer();
    }

    function renderQuestions(showAnswer = false) {
      const list = generatedQuestions.map(q => {
        return showAnswer ? `${q.display} = ${q.answer}` : q.display;
      });
      document.getElementById('questionList').innerHTML = list.join('<br>');
    }

    function showAnswers() {
      renderQuestions(true);
    }
  </script>
</body>
</html>
